/*
 * ENUM Discoverer. ENUM Demonstration software, demonstrating the potential of ENUM.
 * 
 * Copyright (C) 2009 SIDN and ISOC.nl
 * 
 * This file is part of ENUM Discoverer.
 *
 * ENUM Discoverer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ENUM Discoverer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ENUM Discoverer.  If not, see <http://www.gnu.org/licenses/>.
 */

package nl.sidn.enumdiscoverer;

import org.xbill.DNS.Lookup;

import nl.sidn.enumdiscoverer.startup.StartupHelper;
import nl.sidn.enumdiscoverer.ui.about.AboutActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

/**
 * The preferences UI for the application
 * @author	Grant Patterson (grant.patterson@catalyst.net.nz)
 */
public class EditPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {

	static final String TAG = LogConfig.getLogTag(EditPreferences.class);
	// whether DEBUG level logging is enabled (whether globally, or explicitly for this log tag)
	static final boolean DEBUG = LogConfig.isDebug(TAG);
	// whether VERBOSE level logging is enabled
	static final boolean VERBOSE = LogConfig.VERBOSE;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		addPreferencesFromResource(R.xml.preferences);
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(this);
	}
	
	@Override
	protected void onDestroy() {
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.unregisterOnSharedPreferenceChangeListener(this);
		
		super.onDestroy();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.preferences, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		case R.id.about:
			showAboutPage();
			return true;
		case R.id.reset:
			resetToDefaults();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		
		if (DEBUG) Log.d(TAG, "Preference change detected: " + key);
		
		if ( key.equals(getString( R.string.pref_enumsync_switch_key ))) {
			
			boolean syncOn = sharedPreferences.getBoolean(key, true);
			
			if (syncOn) {
				if (VERBOSE) Log.v(TAG, "Scheduling EnumSyncService");
				StartupHelper.resetSyncScheduling(this);
			} else {
				if (VERBOSE) Log.v(TAG, "Cancelling EnumSyncService schedule");
				StartupHelper.cancelEnumSync(this);
			}
			
			// don't worry about stopping the service. Let it finish its current sync
			
		} else if ( key.equals(getString( R.string.pref_enumsync_interval_key ))) {
			
			if (StartupHelper.isSyncEnabled(this)) {
				StartupHelper.resetSyncScheduling(this);
			}
			
		} else if ( key.equals(getString( R.string.pref_incall_switch_key))) {
			
			boolean incallEnabled = sharedPreferences.getBoolean(key, true);
			StartupHelper.enableIncallScreen(this, incallEnabled);
			
		} else if (   key.equals(getString( R.string.pref_use_custom_dns_key))
				   || key.equals(getString( R.string.pref_custom_dns_key))     ) {
			
			// clear dnsjava's cache
			Lookup.refreshDefault();
		}
	}
	
	/**
	 * 
	 * @param prefs
	 * @param context
	 * @return The configured custom DNS servers, or null if custom DNS servers is switched off
	 */
	public static String[] getCustomDnsServers(SharedPreferences prefs, Context context) {
		
		// key for the useCustomDns preference
		String useCustomDnsKey = context.getString(R.string.pref_use_custom_dns_key);
		
		if (!prefs.getBoolean(useCustomDnsKey, false))
			return null;
		
		// look up the custom DNS preference
		String servers = prefs.getString(context.getString(R.string.pref_custom_dns_key), null);
			
		if (servers == null)
			return null;
			
		servers = servers.trim();
		if (servers.length() == 0)
			return null;
			
		return servers.split(",");
	}
	
	private void showAboutPage() {
		
		startActivity(new Intent(this, AboutActivity.class));
	}
	
	private void resetToDefaults() {
		
		if (DEBUG) Log.d(TAG, "Resetting preferences to defaults");
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		// clear the preferences
		prefs.edit().clear().commit();
		// reset defaults
		PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
		
		// refresh displayed values by restarting activity (a hack, but apparently there
		// isn't a nicer way)
		finish();
		startActivity(getIntent());
	}

}
